package com.egao.api.controller.system;


import cn.hutool.core.util.StrUtil;
import com.egao.common.core.annotation.ApiPageParam;
import com.egao.common.core.annotation.OperLog;
import com.egao.common.core.damon.results.PageResult2;
import com.egao.common.core.web.BaseController;
import com.egao.common.core.web.JsonResult;
import com.egao.common.system.entity.User;
import com.egao.common.system.service.OperRecordService;
import com.egao.common.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * api登录相关接口
 * Created by wangfan on 2019-05-29 下午 3:43.
 * http://localhost/swagger-ui.html
 */
@RequestMapping("/api/user")
@RestController
@Api(value = "用户API",tags = {"用户API"})
public class ApiUserController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private OperRecordService operRecordService;


    /**
     * 分页查询列表
     */
    @PreAuthorize("hasAuthority('sys:user:list')")
    @ApiOperation(value = "用户信息列表",notes = "" +
            //"organization_id int 组织id 默认值:4\n" +
            "limit:每页显示几行 必填\n" +
            "page:第几页 必填\n" +
            "customerId 客户id\n" +
            "username 帐号\n" +
            "nickName 姓名\n" +
            "type 类型 司机,车队,货代,平台用户\n" +
            "",httpMethod = "POST")
    @ApiPageParam
    @PostMapping("/page")
    public JsonResult list(PageResult2<T> page, User user) throws Exception{
        return userService.list(page, user, getLoginUser());
    }

    /**
     * 分页查询列表
     */
    @PreAuthorize("hasAuthority('sys:user:list')")
    @ApiOperation(value = "加密手机号码",notes = "" +
            //"organization_id int 组织id 默认值:4\n" +
            "limit:每页显示几行 必填\n" +
            "page:第几页 必填\n" +
            "customerId 客户id\n" +
            "username 帐号\n" +
            "nickName 姓名\n" +
            "type 类型 司机,车队,货代,平台用户\n" +
            "",httpMethod = "POST")
    @ApiPageParam
    @PostMapping("/md5Phone")
    public JsonResult md5Phone(PageResult2<T> page, User user) throws Exception{
        return userService.md5Phone(page, user, getLoginUser());
    }

    /**
     * 添加个人信息
     */
    @PreAuthorize("hasAuthority('sys:user:save')")
    @PostMapping("/save")
    @ApiOperation(value = "用户保存",notes = "" +
            //"organization_id int 组织id 默认值:4\n" +
            "username varchar 账号 必填\n" +
            "nickName varchar 姓名 必填\n" +
            "password varchar 密码 必填\n" +
            "phone varchar 手机号 必填\n" +
            "roleIds 角色id 必填\n" +
            "例子:{\"username\":\"热热热\",\"password\":\"123123\",\"phone\":\"13186850898\",\"roleIds\":[1,2]}" +
            "",httpMethod = "POST")
    public JsonResult save(@RequestBody User user, HttpServletRequest request) {
        try {
            return userService.apiSave2(user);
        } catch (Exception e) {
            return JsonResult.error("用户名重复");
        }
    }

    /**
     * 添加个人信息
     */
    @PreAuthorize("hasAuthority('sys:user:saveCustomerStaff')")
    @OperLog(value = "用户管理", desc = "货代公司添加自己的员工帐号", result = true)
    @PostMapping("/saveCustomerStaff")
    @ApiOperation(value = "货代公司添加自己的员工帐号,默认的角色",notes = "" +
            //"organization_id int 组织id 默认值:4\n" +
            "customerId varchar 货代id 必填\n" +
            "username varchar 账号 必填\n" +
            "nickName varchar 姓名 必填\n" +
            "password varchar 密码 必填\n" +
            "phone varchar 手机号 必填\n" +
//            "roleIds 角色id\n" +
//            "例子:{\"customerId\":\"1\",\"username\":\"aaaa\",\"password\":\"123123\",\"phone\":\"13186850891\"}" +
            "",httpMethod = "POST")
    public JsonResult saveCustomerStaff(User user, HttpServletRequest request) {
        try {
            return userService.saveCustomerStaff(user);
        } catch (Exception e) {
            return JsonResult.error("用户名重复");
        }
    }

    /**
     * 修改个人信息
     */
    @PreAuthorize("hasAuthority('sys:user:update')")
    @OperLog(value = "角色修改", desc = "角色修改", result = true)
    @PostMapping("/updateUser")
    @ApiOperation(value = "角色修改",notes =
            "userId varchar id\n" +
            "nickName varchar 昵称\n" +
            "phone varchar 手机号\n" +
            "",httpMethod = "POST")
    public JsonResult updateUser(User user, HttpServletRequest request) {
        return userService.updateUser(user, getLoginUser());
    }

    /**
     * 修改个人信息
     */
    @PreAuthorize("hasAuthority('sys:user:update')")
    @OperLog(value = "角色修改", desc = "角色修改", result = true)
    @PostMapping("/updateRole")
    @ApiOperation(value = "角色修改",notes =
            "userId varchar id\n" +
            "roleIds 角色id\n" +
            "例子:{\"userId\":\"1\",\"roleIds\":[1,2]}" +
            "",httpMethod = "POST")
    public JsonResult updateRole(@RequestBody User user, HttpServletRequest request) {
        user.setState(null);  // 状态不能修改
        user.setPassword(null);  // 密码不能修改
        user.setUsername(null);  // 账号不能修改
        if (userService.updateUser2(user, getLoginUser())) {
            return JsonResult.ok("修改成功");
        }
        return JsonResult.error("修改失败");
    }


    /**
     * 密码修改
     */
    @PreAuthorize("hasAuthority('sys:user:update')")
    @OperLog(value = "用户管理", desc = "密码修改", result = true)
    @ApiOperation(value = "密码修改",notes = "" +
            "id (user表的id)用户id必填\n" +
            "oldPsw 原来的密码 必填\n" +
            "newPsw 新密码 必填\n" +
            "",httpMethod = "POST")
    @PostMapping("/psw/update")
    public JsonResult update(String id, String oldPsw, String newPsw, HttpServletRequest request) {
        if (StrUtil.hasBlank(id, oldPsw, newPsw)) {
            return JsonResult.error("参数不能为空");
        }
        User u = getLoginUser();
        if (u == null) {
            return JsonResult.error("未登录");
        }
        User user = new User();
        user.setUserId(Integer.valueOf(id));
        user.setPasswordorigin(newPsw);
        user.setPassword(userService.encodePsw(newPsw));
        if (!userService.comparePsw(userService.getUserById(user).getPassword(), oldPsw)) {
            return JsonResult.error("原密码输入不正确");
        }
        return userService.updatePsw(user, u);
    }


    /**
     * 密码修改
     */
    @PreAuthorize("hasAuthority('sys:user:update')")
    @OperLog(value = "用户管理", desc = "密码修改", result = true)
    @ApiOperation(value = "密码修改",notes = "" +
            "id (user表的id)用户id必填\n" +
            "oldPsw 原来的密码 必填\n" +
            "newPsw 新密码 必填\n" +
            "",httpMethod = "POST")
    @PostMapping("/psw/update2")
    public JsonResult update2(String id, String oldPsw, String newPsw, HttpServletRequest request) {
        if (StrUtil.hasBlank(id, oldPsw, newPsw)) {
            return JsonResult.error("参数不能为空");
        }
        User u = getLoginUser();
        if (u == null) {
            return JsonResult.error("未登录");
        }
        User user = new User();
        user.setUserId(Integer.valueOf(id));
        user.setPasswordorigin(newPsw);
        user.setPassword(userService.encodePsw(newPsw));
        return userService.updatePsw(user, u);
    }

    /**
     * 添加角色
     */
    @PreAuthorize("hasAuthority('sys:user:save')")
    @OperLog(value = "用户管理", desc = "添加角色", result = true)
    @ApiOperation(value = "添加角色",notes = "" +
            "userId user id 必填\n" +
            "roleId role id 必填\n" +
            "",httpMethod = "POST")
    @PostMapping("/add/role")
    public JsonResult addRole(User user) {
        if (userService.saveUserRole(user)) {
            return JsonResult.error("添加成功");
        }
        return JsonResult.error("添加失败");
    }


    @PreAuthorize("hasAuthority('sys:user:remove')")
    @OperLog(value = "用户管理", desc = "删除")
    @ApiOperation(value = "删除用户",notes = "" +
            "userId user id 必填\n" +
            "",httpMethod = "POST")
    @PostMapping("/remove/user")
    public JsonResult remove(User user) {
        if (userService.removeUser(user, getLoginUser())) {
            return JsonResult.ok("删除成功");
        }
        return JsonResult.error("删除失败");
    }

    /**
     * 删除角色
     */
    @PreAuthorize("hasAuthority('sys:user:remove')")
    @OperLog(value = "用户管理", desc = "删除角色")
    @ApiOperation(value = "删除角色",notes = "" +
            "userId user id 必填\n" +
            "roleId role id 必填\n" +
            "",httpMethod = "POST")
    @PostMapping("/remove/role")
    public JsonResult removeRole(User user) {
        if (userService.removeUserRole(user)) {
            return JsonResult.error("删除成功");
        }
        return JsonResult.error("删除失败");
    }

    /**
     * 删除用户所有角色
     */
    @PreAuthorize("hasAuthority('sys:user:remove')")
    @OperLog(value = "用户管理", desc = "删除用户所有角色")
    @ApiOperation(value = "删除角色",notes = "" +
            "userId user id 必填\n" +
            "",httpMethod = "POST")
    @PostMapping("/remove/roleAll")
    public JsonResult removeRoleAll(User user) {
        if (userService.removeRoleAll(user)) {
            return JsonResult.error("删除成功");
        }
        return JsonResult.error("删除失败");
    }

}
